// 游戏主脚本

// 游戏状态管理
const gameState = {
    currentScreen: 'start',
    isRunning: false,
    isPaused: false,
    score: 0,
    health: 100,
    time: 0,
    timerInterval: null,
    player: null,
    enemies: [],
    bullets: [],
    weapons: [
        { name: '步枪', damage: 25, ammo: 30, maxAmmo: 120, fireRate: 500 },
        { name: '霰弹枪', damage: 15, ammo: 8, maxAmmo: 40, fireRate: 800 },
        { name: '狙击枪', damage: 100, ammo: 5, maxAmmo: 20, fireRate: 1200 }
    ],
    currentWeapon: 0,
    lastShotTime: 0,
    map: [],
    flowers: [], // 新增：鲜花动画数组
    keys: {
        w: false,
        a: false,
        s: false,
        d: false,
        space: false
    },
    mouse: {
        x: 0,
        y: 0,
        down: false
    }
};

// 游戏常量
const CANVAS_WIDTH = 1280;
const CANVAS_HEIGHT = 720;
const TILE_SIZE = 32;
const PLAYER_SPEED = 5;
const JUMP_FORCE = 15;
const GRAVITY = 0.8;
const ENEMY_SPEED = 2;
const BULLET_SPEED = 15;
const ENEMY_SPAWN_RATE = 3000; // 毫秒
const MAX_ENEMIES = 8;

// 声明全局变量，但在DOM加载完成后再初始化
let screens, buttons, hudElements, canvas, ctx;

// 初始化DOM元素引用
function initDOM() {
    console.log('Initializing DOM elements...');
    
    screens = {
        start: document.getElementById('start-screen'),
        instructions: document.getElementById('instructions-screen'),
        game: document.getElementById('game-screen'),
        pause: document.getElementById('pause-screen'),
        gameOver: document.getElementById('game-over-screen'),
        victory: document.getElementById('victory-screen')
    };

    buttons = {
        start: document.getElementById('start-button'),
        instructions: document.getElementById('instructions-button'),
        back: document.getElementById('back-button'),
        pause: document.getElementById('pause-button'),
        resume: document.getElementById('resume-button'),
        restart: document.getElementById('restart-button'),
        quit: document.getElementById('quit-button'),
        playAgain: document.getElementById('play-again-button'),
        backToMenu: document.getElementById('back-to-menu-button'),
        victoryAgain: document.getElementById('victory-again-button'),
        victoryMenu: document.getElementById('victory-menu-button')
    };

    hudElements = {
        healthFill: document.getElementById('health-fill'),
        healthText: document.getElementById('health-text'),
        ammoText: document.getElementById('ammo-text'),
        weaponText: document.getElementById('weapon-text'),
        scoreText: document.getElementById('score-text'),
        timerText: document.getElementById('timer-text'),
        finalScore: document.getElementById('final-score'),
        finalTime: document.getElementById('final-time'),
        victoryScore: document.getElementById('victory-score'),
        victoryTime: document.getElementById('victory-time')
    };

    canvas = document.getElementById('game-canvas');
    ctx = canvas.getContext('2d');
    canvas.width = CANVAS_WIDTH;
    canvas.height = CANVAS_HEIGHT;
    
    console.log('Canvas initialized:', canvas);
    console.log('Start button element:', buttons.start);
    console.log('Start screen element:', screens.start);
    
    // 验证关键按钮是否存在
    if (!buttons.start) {
        console.error('CRITICAL: Start button not found!');
    } else {
        console.log('Start button successfully found:', buttons.start);
    }
    
    // 验证所有按钮
    Object.entries(buttons).forEach(([key, button]) => {
        if (!button) {
            console.warn(`Warning: Button '${key}' not found in the DOM`);
        }
    });
}

// 初始化事件监听
function initEventListeners() {
    console.log('Initializing event listeners...');
    
    // 直接获取按钮元素并绑定事件，作为备选方案
    const startButton = document.getElementById('start-button');
    if (startButton) {
        console.log('Found start button directly:', startButton);
        // 使用两种方式绑定事件，确保能够触发
        startButton.onclick = function() {
            console.log('Start button clicked via onclick property');
            switchScreen('game');
        };
        startButton.addEventListener('click', function(event) {
            console.log('Start button clicked via addEventListener');
            // 阻止事件冒泡，避免重复触发
            event.stopPropagation();
        });
    } else {
        console.error('Could not find start button directly!');
    }
    
    // 屏幕切换按钮
    if (buttons && buttons.start) {
        console.log('Binding event to buttons.start');
        buttons.start.addEventListener('click', () => switchScreen('game'));
    }
    if (buttons && buttons.instructions) {
        buttons.instructions.addEventListener('click', () => switchScreen('instructions'));
    }
    if (buttons && buttons.back) {
        buttons.back.addEventListener('click', () => switchScreen('start'));
    }
    if (buttons && buttons.pause) {
        buttons.pause.addEventListener('click', pauseGame);
    }
    if (buttons && buttons.resume) {
        buttons.resume.addEventListener('click', resumeGame);
    }
    if (buttons && buttons.restart) {
        buttons.restart.addEventListener('click', restartGame);
    }
    if (buttons && buttons.quit) {
        buttons.quit.addEventListener('click', () => switchScreen('start'));
    }
    if (buttons && buttons.playAgain) {
        buttons.playAgain.addEventListener('click', restartGame);
    }
    if (buttons && buttons.backToMenu) {
        buttons.backToMenu.addEventListener('click', () => switchScreen('start'));
    }
    if (buttons && buttons.victoryAgain) {
        buttons.victoryAgain.addEventListener('click', restartGame);
    }
    if (buttons && buttons.victoryMenu) {
        buttons.victoryMenu.addEventListener('click', () => switchScreen('start'));
    }

    // 键盘控制
    window.addEventListener('keydown', (e) => {
        switch(e.key.toLowerCase()) {
            case 'w': gameState.keys.w = true; break;
            case 'a': gameState.keys.a = true; break;
            case 's': gameState.keys.s = true; break;
            case 'd': gameState.keys.d = true; break;
            case ' ': gameState.keys.space = true; break;
            case '1': gameState.currentWeapon = 0; updateHUD(); break;
            case '2': gameState.currentWeapon = 1; updateHUD(); break;
            case '3': gameState.currentWeapon = 2; updateHUD(); break;
            case 'escape': gameState.isPaused ? resumeGame() : pauseGame(); break;
        }
    });

    window.addEventListener('keyup', (e) => {
        switch(e.key.toLowerCase()) {
            case 'w': gameState.keys.w = false; break;
            case 'a': gameState.keys.a = false; break;
            case 's': gameState.keys.s = false; break;
            case 'd': gameState.keys.d = false; break;
            case ' ': gameState.keys.space = false; break;
        }
    });

    // 鼠标控制
    canvas.addEventListener('mousemove', (e) => {
        const rect = canvas.getBoundingClientRect();
        gameState.mouse.x = e.clientX - rect.left;
        gameState.mouse.y = e.clientY - rect.top;
    });

    canvas.addEventListener('mousedown', () => {
        gameState.mouse.down = true;
    });

    canvas.addEventListener('mouseup', () => {
        gameState.mouse.down = false;
    });

    canvas.addEventListener('mouseleave', () => {
        gameState.mouse.down = false;
    });
}

// 屏幕切换函数
function switchScreen(screenName) {
    console.log('---------------------');
    console.log('Switching to screen:', screenName);
    
    // 验证屏幕对象是否存在
    if (!screens) {
        console.error('Error: screens object not initialized!');
        // 尝试重新初始化
        initDOM();
        return;
    }
    
    // 显示所有可用屏幕信息
    console.log('Available screens:', Object.keys(screens).filter(key => screens[key]));
    console.log('Missing screens:', Object.keys(screens).filter(key => !screens[key]));
    
    // 隐藏所有屏幕
    Object.entries(screens).forEach(([key, screen]) => {
        if (screen) {
            console.log(`Hiding screen: ${key}`);
            screen.style.display = 'none';
        } else {
            console.warn(`Cannot hide screen: ${key} (not found)`);
        }
    });
    
    // 显示目标屏幕
    if (screens[screenName]) {
        console.log(`Displaying screen: ${screenName}`);
        screens[screenName].style.display = 'flex';
        gameState.currentScreen = screenName;
        console.log('Screen displayed successfully');
    } else {
        console.error('Screen not found:', screenName);
        // 直接通过ID查找并显示
        const directScreen = document.getElementById(screenName + '-screen');
        if (directScreen) {
            console.log(`Found screen directly via ID: ${screenName}-screen`);
            directScreen.style.display = 'flex';
            gameState.currentScreen = screenName;
        }
    }

    // 游戏开始时的初始化
    if (screenName === 'game') {
        console.log('Initializing game...');
        
        // 强制显示游戏画布
        if (canvas) {
            console.log('Ensuring canvas is visible');
            canvas.style.display = 'block';
        }
        
        if (!gameState.isRunning) {
            initGame();
        } else if (gameState.isPaused) {
            resumeGame();
        }
    } else if (screenName !== 'pause') {
        pauseGame();
    }
    console.log('---------------------');
}

// 初始化游戏
function initGame() {
    // 重置游戏状态
    gameState.score = 0;
    gameState.health = 100;
    gameState.time = 0;
    gameState.enemies = [];
    gameState.bullets = [];
    gameState.weapons.forEach(weapon => {
        weapon.ammo = weapon.maxAmmo * 0.25; // 初始弹药为最大容量的1/4
    });
    gameState.currentWeapon = 0;
    gameState.lastShotTime = 0;

    // 创建玩家
    gameState.player = {
        x: CANVAS_WIDTH / 2,
        y: CANVAS_HEIGHT / 2,
        width: 24,
        height: 32,
        velocityX: 0,
        velocityY: 0,
        onGround: true,
        direction: 1
    };

    // 生成地图
    generateMap();

    // 启动游戏循环
    gameState.isRunning = true;
    gameState.isPaused = false;
    updateHUD();
    startGameLoop();
    startEnemySpawner();
    startTimer();
}

// 生成简单的地图
function generateMap() {
    gameState.map = [];
    // 创建边界和一些平台
    for (let y = 0; y < CANVAS_HEIGHT / TILE_SIZE; y++) {
        const row = [];
        for (let x = 0; x < CANVAS_WIDTH / TILE_SIZE; x++) {
            // 边界
            if (x === 0 || x === (CANVAS_WIDTH / TILE_SIZE) - 1 || 
                y === 0 || y === (CANVAS_HEIGHT / TILE_SIZE) - 1) {
                row.push(1);
            } 
            // 地面
            else if (y === (CANVAS_HEIGHT / TILE_SIZE) - 3) {
                row.push(Math.random() > 0.7 ? 0 : 1);
            }
            // 平台
            else if (y === 10 && (x > 10 && x < 20)) {
                row.push(1);
            }
            else if (y === 15 && (x > 30 && x < 40)) {
                row.push(1);
            }
            else {
                row.push(0);
            }
        }
        gameState.map.push(row);
    }
}

// 开始游戏循环
let gameLoopId;
function startGameLoop() {
    function gameLoop() {
        if (!gameState.isPaused && gameState.isRunning) {
            update();
            render();
        }
        gameLoopId = requestAnimationFrame(gameLoop);
    }
    gameLoop();
}

// 启动敌人生成器
let enemySpawnerId;
function startEnemySpawner() {
    clearInterval(enemySpawnerId);
    enemySpawnerId = setInterval(() => {
        if (!gameState.isPaused && gameState.enemies.length < MAX_ENEMIES) {
            spawnEnemy();
        }
    }, ENEMY_SPAWN_RATE);
}

// 启动计时器
function startTimer() {
    clearInterval(gameState.timerInterval);
    gameState.timerInterval = setInterval(() => {
        if (!gameState.isPaused && gameState.isRunning) {
            gameState.time++;
            updateTimer();
        }
    }, 1000);
}

// 更新计时器显示
function updateTimer() {
    const minutes = Math.floor(gameState.time / 60).toString().padStart(2, '0');
    const seconds = (gameState.time % 60).toString().padStart(2, '0');
    hudElements.timerText.textContent = `${minutes}:${seconds}`;
}

// 生成敌人
function spawnEnemy() {
    // 随机在地图边缘生成敌人
    const side = Math.floor(Math.random() * 4);
    let x, y;
    
    switch(side) {
        case 0: // 顶部
            x = Math.random() * CANVAS_WIDTH;
            y = 50;
            break;
        case 1: // 右侧
            x = CANVAS_WIDTH - 50;
            y = Math.random() * CANVAS_HEIGHT;
            break;
        case 2: // 底部
            x = Math.random() * CANVAS_WIDTH;
            y = CANVAS_HEIGHT - 50;
            break;
        case 3: // 左侧
            x = 50;
            y = Math.random() * CANVAS_HEIGHT;
            break;
    }

    const enemy = {
        x: x,
        y: y,
        width: 24,
        height: 32,
        health: 100,
        damage: 10,
        lastAttackTime: 0,
        attackCooldown: 2000,
        velocityX: 0,
        velocityY: 0,
        onGround: false
    };

    gameState.enemies.push(enemy);
}

// 更新游戏状态
function update() {
    updatePlayer();
    updateEnemies();
    updateBullets();
    updateFlowers(); // 新增：更新鲜花动画
    checkCollisions();
    checkGameOver();
    checkVictory();
}

// 新增：创建鲜花动画函数
function createFlower(x, y) {
    gameState.flowers.push({
        x: x,
        y: y,
        size: 8,
        maxSize: 24,
        color: '#ff69b4', // 粉红色
        alpha: 1,
        phase: 'growing', // growing, blooming, fading
        frame: 0,
        petals: 8 // 花瓣数量
    });
}

// 新增：更新鲜花动画
function updateFlowers() {
    for (let i = gameState.flowers.length - 1; i >= 0; i--) {
        const flower = gameState.flowers[i];
        flower.frame++;
        
        switch (flower.phase) {
            case 'growing':
                flower.size += 0.5;
                if (flower.size >= flower.maxSize * 0.8) {
                    flower.phase = 'blooming';
                    flower.frame = 0;
                }
                break;
            case 'blooming':
                if (flower.frame > 60) { // 盛开持续1秒
                    flower.phase = 'fading';
                }
                break;
            case 'fading':
                flower.alpha -= 0.02;
                if (flower.alpha <= 0) {
                    gameState.flowers.splice(i, 1);
                }
                break;
        }
    }
}

// 新增：渲染鲜花动画
function renderFlowers() {
    ctx.save();
    gameState.flowers.forEach(flower => {
        ctx.globalAlpha = flower.alpha;
        ctx.fillStyle = flower.color;
        
        // 绘制花蕊
        ctx.beginPath();
        ctx.arc(flower.x, flower.y, flower.size * 0.3, 0, Math.PI * 2);
        ctx.fill();
        ctx.fillStyle = '#ffcc00'; // 黄色花蕊
        ctx.beginPath();
        ctx.arc(flower.x, flower.y, flower.size * 0.2, 0, Math.PI * 2);
        ctx.fill();
        
        // 绘制花瓣
        ctx.fillStyle = flower.color;
        for (let i = 0; i < flower.petals; i++) {
            const angle = (Math.PI * 2 / flower.petals) * i;
            const petalX = flower.x + Math.cos(angle) * flower.size * 0.7;
            const petalY = flower.y + Math.sin(angle) * flower.size * 0.7;
            
            ctx.save();
            ctx.translate(petalX, petalY);
            ctx.rotate(angle);
            
            // 绘制椭圆花瓣
            ctx.beginPath();
            ctx.scale(0.5, 1);
            ctx.arc(0, 0, flower.size * 0.4, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        }
    });
    ctx.restore();
}

// 更新玩家
function updatePlayer() {
    const player = gameState.player;
    const currentWeapon = gameState.weapons[gameState.currentWeapon];

    // 移动控制
    player.velocityX = 0;
    if (gameState.keys.a) player.velocityX = -PLAYER_SPEED;
    if (gameState.keys.d) player.velocityX = PLAYER_SPEED;
    
    // 跳跃
    if (gameState.keys.space && player.onGround) {
        player.velocityY = -JUMP_FORCE;
        player.onGround = false;
    }

    // 射击
    if (gameState.mouse.down) {
        const now = Date.now();
        if (now - gameState.lastShotTime > currentWeapon.fireRate && currentWeapon.ammo > 0) {
            fireWeapon();
            gameState.lastShotTime = now;
        }
    }

    // 应用重力
    player.velocityY += GRAVITY;

    // 更新位置
    player.x += player.velocityX;
    player.y += player.velocityY;

    // 检查方向
    if (player.velocityX > 0) player.direction = 1;
    if (player.velocityX < 0) player.direction = -1;

    // 碰撞检测
    checkPlayerMapCollision();
}

// 射击武器
function fireWeapon() {
    const player = gameState.player;
    const currentWeapon = gameState.weapons[gameState.currentWeapon];
    
    if (currentWeapon.ammo <= 0) return;
    
    currentWeapon.ammo--;
    updateHUD();

    // 计算射击方向
    const dx = gameState.mouse.x - player.x - player.width / 2;
    const dy = gameState.mouse.y - player.y - player.height / 2;
    const angle = Math.atan2(dy, dx);

    // 创建子弹
    const bullet = {
        x: player.x + player.width / 2,
        y: player.y + player.height / 2,
        width: 8,
        height: 8,
        velocityX: Math.cos(angle) * BULLET_SPEED,
        velocityY: Math.sin(angle) * BULLET_SPEED,
        damage: currentWeapon.damage
    };

    gameState.bullets.push(bullet);
}

// 更新敌人
function updateEnemies() {
    gameState.enemies.forEach(enemy => {
        const player = gameState.player;
        const dx = player.x - enemy.x;
        const dy = player.y - enemy.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 敌人AI：追踪玩家
        if (distance > 50) {
            enemy.velocityX = (dx / distance) * ENEMY_SPEED;
        } else {
            enemy.velocityX = 0;
            // 攻击玩家
            const now = Date.now();
            if (now - enemy.lastAttackTime > enemy.attackCooldown) {
                attackPlayer(enemy);
                enemy.lastAttackTime = now;
            }
        }

        // 应用重力
        enemy.velocityY += GRAVITY;

        // 更新位置
        enemy.x += enemy.velocityX;
        enemy.y += enemy.velocityY;

        // 碰撞检测
        checkEnemyMapCollision(enemy);
    });
}

// 敌人攻击玩家
function attackPlayer(enemy) {
    gameState.health -= enemy.damage;
    if (gameState.health < 0) gameState.health = 0;
    updateHUD();
}

// 更新子弹
function updateBullets() {
    gameState.bullets = gameState.bullets.filter(bullet => {
        // 更新位置
        bullet.x += bullet.velocityX;
        bullet.y += bullet.velocityY;

        // 移除超出屏幕的子弹
        return bullet.x > 0 && bullet.x < CANVAS_WIDTH && 
               bullet.y > 0 && bullet.y < CANVAS_HEIGHT;
    });
}

// 检查碰撞
function checkCollisions() {
    checkBulletEnemyCollisions();
    checkPlayerEnemyCollisions();
}

// 检查子弹和敌人的碰撞
function checkBulletEnemyCollisions() {
    gameState.bullets = gameState.bullets.filter(bullet => {
        let bulletHit = false;
        
        gameState.enemies = gameState.enemies.filter(enemy => {
            if (checkCollision(bullet, enemy)) {
                bulletHit = true;
                enemy.health -= bullet.damage;
                
                if (enemy.health <= 0) {
                    // 敌人死亡，增加分数
                    gameState.score += 100;
                    updateHUD();
                    // 新增：在敌人死亡位置创建鲜花动画
                    createFlower(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                    return false;
                }
            }
            return true;
        });
        
        return !bulletHit;
    });
}

// 检查玩家和敌人的碰撞
function checkPlayerEnemyCollisions() {
    gameState.enemies.forEach(enemy => {
        if (checkCollision(gameState.player, enemy)) {
            // 简单的碰撞处理：推开敌人
            const dx = gameState.player.x - enemy.x;
            const dy = gameState.player.y - enemy.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 0) {
                const pushX = (dx / distance) * 10;
                const pushY = (dy / distance) * 10;
                
                gameState.player.x += pushX;
                enemy.x -= pushX;
            }
        }
    });
}

// 碰撞检测函数
function checkCollision(obj1, obj2) {
    return obj1.x < obj2.x + obj2.width &&
           obj1.x + obj1.width > obj2.x &&
           obj1.y < obj2.y + obj2.height &&
           obj1.y + obj1.height > obj2.y;
}

// 检查玩家和地图的碰撞
function checkPlayerMapCollision() {
    const player = gameState.player;
    player.onGround = false;

    // 检查与地图块的碰撞
    const leftTile = Math.floor(player.x / TILE_SIZE);
    const rightTile = Math.floor((player.x + player.width) / TILE_SIZE);
    const topTile = Math.floor(player.y / TILE_SIZE);
    const bottomTile = Math.floor((player.y + player.height) / TILE_SIZE);

    // 左右碰撞
    if (gameState.map[topTile] && gameState.map[topTile][leftTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][leftTile] === 1) {
        player.x = (leftTile + 1) * TILE_SIZE;
        player.velocityX = 0;
    }
    if (gameState.map[topTile] && gameState.map[topTile][rightTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][rightTile] === 1) {
        player.x = rightTile * TILE_SIZE - player.width;
        player.velocityX = 0;
    }

    // 上下碰撞
    if (gameState.map[bottomTile] && gameState.map[bottomTile][leftTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][rightTile] === 1) {
        player.y = bottomTile * TILE_SIZE - player.height;
        player.velocityY = 0;
        player.onGround = true;
    }
    if (gameState.map[topTile] && gameState.map[topTile][leftTile] === 1 ||
        gameState.map[topTile] && gameState.map[topTile][rightTile] === 1) {
        player.y = (topTile + 1) * TILE_SIZE;
        player.velocityY = 0;
    }

    // 边界检查
    if (player.x < 0) player.x = 0;
    if (player.x + player.width > CANVAS_WIDTH) player.x = CANVAS_WIDTH - player.width;
    if (player.y < 0) player.y = 0;
    if (player.y + player.height > CANVAS_HEIGHT) {
        player.y = CANVAS_HEIGHT - player.height;
        player.velocityY = 0;
        player.onGround = true;
    }
}

// 检查敌人和地图的碰撞
function checkEnemyMapCollision(enemy) {
    enemy.onGround = false;

    // 检查与地图块的碰撞
    const leftTile = Math.floor(enemy.x / TILE_SIZE);
    const rightTile = Math.floor((enemy.x + enemy.width) / TILE_SIZE);
    const topTile = Math.floor(enemy.y / TILE_SIZE);
    const bottomTile = Math.floor((enemy.y + enemy.height) / TILE_SIZE);

    // 左右碰撞
    if (gameState.map[topTile] && gameState.map[topTile][leftTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][leftTile] === 1) {
        enemy.x = (leftTile + 1) * TILE_SIZE;
        enemy.velocityX = 0;
    }
    if (gameState.map[topTile] && gameState.map[topTile][rightTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][rightTile] === 1) {
        enemy.x = rightTile * TILE_SIZE - enemy.width;
        enemy.velocityX = 0;
    }

    // 上下碰撞
    if (gameState.map[bottomTile] && gameState.map[bottomTile][leftTile] === 1 ||
        gameState.map[bottomTile] && gameState.map[bottomTile][rightTile] === 1) {
        enemy.y = bottomTile * TILE_SIZE - enemy.height;
        enemy.velocityY = 0;
        enemy.onGround = true;
    }
    if (gameState.map[topTile] && gameState.map[topTile][leftTile] === 1 ||
        gameState.map[topTile] && gameState.map[topTile][rightTile] === 1) {
        enemy.y = (topTile + 1) * TILE_SIZE;
        enemy.velocityY = 0;
    }

    // 边界检查
    if (enemy.x < 0) enemy.x = 0;
    if (enemy.x + enemy.width > CANVAS_WIDTH) enemy.x = CANVAS_WIDTH - enemy.width;
    if (enemy.y < 0) enemy.y = 0;
    if (enemy.y + enemy.height > CANVAS_HEIGHT) {
        enemy.y = CANVAS_HEIGHT - enemy.height;
        enemy.velocityY = 0;
        enemy.onGround = true;
    }
}

// 更新HUD
function updateHUD() {
    const currentWeapon = gameState.weapons[gameState.currentWeapon];
    
    hudElements.healthFill.style.width = `${gameState.health}%`;
    hudElements.healthText.textContent = Math.floor(gameState.health);
    hudElements.ammoText.textContent = `${Math.floor(currentWeapon.ammo)}/${currentWeapon.maxAmmo}`;
    hudElements.weaponText.textContent = currentWeapon.name;
    hudElements.scoreText.textContent = gameState.score;
}

// 检查游戏结束
function checkGameOver() {
    if (gameState.health <= 0) {
        gameOver();
    }
}

// 检查胜利条件
function checkVictory() {
    // 这里可以根据实际需求设置胜利条件
    // 比如达到一定分数或消灭一定数量的敌人
    if (gameState.score >= 5000) {
        victory();
    }
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    clearInterval(enemySpawnerId);
    clearInterval(gameState.timerInterval);
    cancelAnimationFrame(gameLoopId);
    
    // 更新游戏结束界面
    const minutes = Math.floor(gameState.time / 60).toString().padStart(2, '0');
    const seconds = (gameState.time % 60).toString().padStart(2, '0');
    hudElements.finalScore.textContent = gameState.score;
    hudElements.finalTime.textContent = `${minutes}:${seconds}`;
    
    switchScreen('gameOver');
}

// 游戏胜利
function victory() {
    gameState.isRunning = false;
    clearInterval(enemySpawnerId);
    clearInterval(gameState.timerInterval);
    cancelAnimationFrame(gameLoopId);
    
    // 更新胜利界面
    const minutes = Math.floor(gameState.time / 60).toString().padStart(2, '0');
    const seconds = (gameState.time % 60).toString().padStart(2, '0');
    hudElements.victoryScore.textContent = gameState.score;
    hudElements.victoryTime.textContent = `${minutes}:${seconds}`;
    
    switchScreen('victory');
}

// 暂停游戏
function pauseGame() {
    if (!gameState.isRunning) return;
    
    gameState.isPaused = true;
    switchScreen('pause');
}

// 继续游戏
function resumeGame() {
    if (!gameState.isRunning) return;
    
    gameState.isPaused = false;
    switchScreen('game');
}

// 重新开始游戏
function restartGame() {
    gameState.isRunning = false;
    clearInterval(enemySpawnerId);
    clearInterval(gameState.timerInterval);
    cancelAnimationFrame(gameLoopId);
    
    switchScreen('game');
}

// 渲染游戏
function render() {
    // 清空画布
    ctx.fillStyle = '#1a1a2e';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 渲染地图
    renderMap();

    // 渲染玩家
    renderPlayer();

    // 渲染敌人
    renderEnemies();

    // 渲染子弹
    renderBullets();
    
    // 新增：渲染鲜花动画
    renderFlowers();
}

// 新增：创建鲜花动画函数
function createFlower(x, y) {
  gameState.flowers.push({
    x: x,
    y: y,
    size: 8,
    maxSize: 24,
    color: '#ff69b4', // 粉红色
    alpha: 1,
    phase: 'growing', // growing, blooming, fading
    frame: 0,
    petals: 8 // 花瓣数量
  });
}

// 新增：更新鲜花动画
function updateFlowers() {
  for (let i = gameState.flowers.length - 1; i >= 0; i--) {
    const flower = gameState.flowers[i];
    flower.frame++;
    
    switch (flower.phase) {
      case 'growing':
        flower.size += 0.5;
        if (flower.size >= flower.maxSize * 0.8) {
          flower.phase = 'blooming';
          flower.frame = 0;
        }
        break;
      case 'blooming':
        if (flower.frame > 60) { // 盛开持续1秒
          flower.phase = 'fading';
        }
        break;
      case 'fading':
        flower.alpha -= 0.02;
        if (flower.alpha <= 0) {
          gameState.flowers.splice(i, 1);
        }
        break;
    }
  }
}

// 新增：渲染鲜花动画
function renderFlowers() {
  ctx.save();
  gameState.flowers.forEach(flower => {
    ctx.globalAlpha = flower.alpha;
    ctx.fillStyle = flower.color;
    
    // 绘制花蕊
    ctx.beginPath();
    ctx.arc(flower.x, flower.y, flower.size * 0.3, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = '#ffcc00'; // 黄色花蕊
    ctx.beginPath();
    ctx.arc(flower.x, flower.y, flower.size * 0.2, 0, Math.PI * 2);
    ctx.fill();
    
    // 绘制花瓣
    ctx.fillStyle = flower.color;
    for (let i = 0; i < flower.petals; i++) {
      const angle = (Math.PI * 2 / flower.petals) * i;
      const petalX = flower.x + Math.cos(angle) * flower.size * 0.7;
      const petalY = flower.y + Math.sin(angle) * flower.size * 0.7;
      
      ctx.save();
      ctx.translate(petalX, petalY);
      ctx.rotate(angle);
      
      // 绘制椭圆花瓣
      ctx.beginPath();
      ctx.scale(0.5, 1);
      ctx.arc(0, 0, flower.size * 0.4, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
    }
  });
  ctx.restore();
}

// 敌人生成器
function spawnEnemy() {
      if (gameState.enemies.length < 5 && gameState.enemiesKilled < gameState.targetEnemies) {
        const sides = ['top', 'bottom', 'left', 'right'];
        const side = sides[Math.floor(Math.random() * sides.length)];
        let x, y;
        
        switch (side) {
          case 'top':
            x = Math.random() * canvas.width;
            y = -50;
            break;
          case 'bottom':
            x = Math.random() * canvas.width;
            y = canvas.height + 50;
            break;
          case 'left':
            x = -50;
            y = Math.random() * canvas.height;
            break;
          case 'right':
            x = canvas.width + 50;
            y = Math.random() * canvas.height;
            break;
        }
        
        // 根据关卡调整敌人属性
        const health = 50 + (gameState.level - 1) * 20;
        const speed = 2 + (gameState.level - 1) * 0.5;
        
        gameState.enemies.push({
          x: x,
          y: y,
          width: 32,
          height: 48,
          health: health,
          maxHealth: health,
          speed: speed,
          color: `hsl(${Math.random() * 60 + 180}, 70%, 50%)` // 敌人颜色
        });
      }
    }

    // 检测碰撞检测
    function checkCollisions() {
      checkBulletEnemyCollisions();
      checkPlayerEnemyCollisions();
      checkPlayerMapCollisions();
      checkEnemiesMapCollisions();
    }

    // 子弹与敌人碰撞检测
    function checkBulletEnemyCollisions() {
      checkBulletEnemyCollisions();
      checkPlayerEnemyCollisions();
    }

    // 更新游戏状态
    function update() {
      if (!gameState.isRunning || gameState.isPaused || gameState.isGameOver || gameState.isVictory) return;
      
      // 更新计时器
      gameState.timer += 1 / 60;
      
      // 更新玩家
      updatePlayer();
      
      // 更新敌人
      updateEnemies();
      
      // 更新子弹
      updateBullets();
      
      // 新增：更新鲜花动画
      updateFlowers();
      
      // 检测碰撞
      checkCollisions();
      
      // 更新HUD
      updateHUD();
      
      // 检查游戏结束条件
      checkGameOverCondition();
    }

    // 更新HUD
    function updateHUD() {
      const currentWeapon = gameState.weapons[gameState.currentWeapon];
      
      hudElements.healthFill.style.width = `${gameState.health}%`;
      hudElements.healthText.textContent = Math.floor(gameState.health);
      hudElements.ammoText.textContent = `${Math.floor(currentWeapon.ammo)}/${currentWeapon.maxAmmo}`;
      hudElements.weaponText.textContent = currentWeapon.name;
      hudElements.scoreText.textContent = gameState.score;
    }

    // 检查游戏结束
    function checkGameOver() {
      if (gameState.health <= 0) {
        gameOver();
      }
    }

    // 检查胜利条件
    function checkVictory() {
      // 这里可以根据实际需求设置胜利条件
      // 比如达到一定分数或消灭一定数量的敌人
      if (gameState.score >= 5000) {
        victory();
      }
    }

    // 游戏结束
    function gameOver() {
      gameState.isRunning = false;
      clearInterval(enemySpawnerId);
      clearInterval(gameState.timerInterval);
      cancelAnimationFrame(gameLoopId);
      
      // 更新游戏结束界面
      const minutes = Math.floor(gameState.time / 60).toString().padStart(2, '0');
      const seconds = (gameState.time % 60).toString().padStart(2, '0');
      hudElements.finalScore.textContent = gameState.score;
      hudElements.finalTime.textContent = `${minutes}:${seconds}`;
      
      switchScreen('gameOver');
    }

    // 游戏胜利
    function victory() {
      gameState.isRunning = false;
      clearInterval(enemySpawnerId);
      clearInterval(gameState.timerInterval);
      cancelAnimationFrame(gameLoopId);
      
      // 更新胜利界面
      const minutes = Math.floor(gameState.time / 60).toString().padStart(2, '0');
      const seconds = (gameState.time % 60).toString().padStart(2, '0');
      hudElements.victoryScore.textContent = gameState.score;
      hudElements.victoryTime.textContent = `${minutes}:${seconds}`;
      
      switchScreen('victory');
    }

    // 暂停游戏
    function pauseGame() {
      if (!gameState.isRunning) return;
      
      gameState.isPaused = true;
      switchScreen('pause');
    }

    // 继续游戏
    function resumeGame() {
      if (!gameState.isRunning) return;
      
      gameState.isPaused = false;
      switchScreen('game');
    }

    // 重新开始游戏
    function restartGame() {
      gameState.isRunning = false;
      clearInterval(enemySpawnerId);
      clearInterval(gameState.timerInterval);
      cancelAnimationFrame(gameLoopId);
      
      switchScreen('game');
    }

// 渲染游戏
function render() {
    // 清空画布
    ctx.fillStyle = '#696969';
    ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    // 渲染地图
    renderMap();

    // 渲染子弹
    renderBullets();

    // 渲染敌人
    renderEnemies();

    // 渲染玩家
    renderPlayer();
    
    // 新增：渲染鲜花动画
    renderFlowers();

    // 渲染准星
    renderCrosshair();
}

// 渲染地图
function renderMap() {
  for (let y = 0; y < gameState.map.length; y++) {
    for (let x = 0; x < gameState.map[y].length; x++) {
      if (gameState.map[y][x] === 1) {
          // 渲染砖块
          ctx.fillStyle = '#8B4513';
          ctx.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
          
          // 添加像素边框
          ctx.strokeStyle = '#000';
          ctx.lineWidth = 2;
          ctx.strokeRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
      }
  }
}

// 渲染玩家
function renderPlayer() {
  const player = gameState.player;
  
  // 渲染玩家身体
  ctx.fillStyle = '#006400';
  ctx.fillRect(player.x, player.y, player.width, player.height);
  
  // 渲染玩家头部
  ctx.fillStyle = '#FFD700';
  ctx.fillRect(player.x + 4, player.y - 8, player.width - 8, 8);
  
  // 渲染武器
  const currentWeapon = gameState.weapons[gameState.currentWeapon];
  ctx.save();
  ctx.translate(player.x + player.width / 2, player.y + player.height / 2);
  
  // 计算武器角度
  const dx = gameState.mouse.x - (player.x + player.width / 2);
  const dy = gameState.mouse.y - (player.y + player.height / 2);
  const angle = Math.atan2(dy, dx);
  
  ctx.rotate(angle);
  
  // 渲染武器
  ctx.fillStyle = '#666';
  ctx.fillRect(0, -2, 20, 4);
  
  ctx.restore();
  
  // 添加像素边框
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 2;
  ctx.strokeRect(player.x, player.y, player.width, player.height);
  ctx.strokeRect(player.x + 4, player.y - 8, player.width - 8, 8);
}

// 渲染敌人
function renderEnemies() {
  gameState.enemies.forEach(enemy => {
      // 渲染敌人身体
      ctx.fillStyle = '#8B0000';
      ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
      
      // 渲染敌人头部
      ctx.fillStyle = '#FF8C00';
      ctx.fillRect(enemy.x + 4, enemy.y - 8, enemy.width - 8, 8);
      
      // 渲染生命值条
      const healthPercent = enemy.health / 100;
      ctx.fillStyle = '#333';
      ctx.fillRect(enemy.x, enemy.y - 12, enemy.width, 4);
      ctx.fillStyle = healthPercent > 0.5 ? '#4CAF50' : healthPercent > 0.25 ? '#FFC107' : '#F44336';
      ctx.fillRect(enemy.x, enemy.y - 12, enemy.width * healthPercent, 4);
      
      // 添加像素边框
      ctx.strokeStyle = '#000';
      ctx.lineWidth = 2;
      ctx.strokeRect(enemy.x, enemy.y, enemy.width, enemy.height);
      ctx.strokeRect(enemy.x + 4, enemy.y - 8, enemy.width - 8, 8);
  });
}

// 渲染子弹
function renderBullets() {
  gameState.bullets.forEach(bullet => {
      ctx.fillStyle = '#FFFF00';
      ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
      
      // 添加像素边框
      ctx.strokeStyle = '#000';
      ctx.lineWidth = 1;
      ctx.strokeRect(bullet.x, bullet.y, bullet.width, bullet.height);
  });
}

// 渲染准星
function renderCrosshair() {
  const x = gameState.mouse.x;
  const y = gameState.mouse.y;
  
  ctx.strokeStyle = '#FFF';
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.moveTo(x - 10, y);
  ctx.lineTo(x + 10, y);
  ctx.moveTo(x, y - 10);
  ctx.lineTo(x, y + 10);
  ctx.stroke();
  
  // 像素风格边框
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(x - 11, y - 1);
  ctx.lineTo(x + 11, y - 1);
  ctx.moveTo(x - 11, y + 1);
  ctx.lineTo(x + 11, y + 1);
  ctx.moveTo(x - 1, y - 11);
  ctx.lineTo(x - 1, y + 11);
  ctx.moveTo(x + 1, y - 11);
  ctx.lineTo(x + 1, y + 11);
  ctx.stroke();
}

// 初始化游戏
function init() {
  console.log('Initializing game application...');
  initDOM(); // 首先初始化DOM元素
  initEventListeners(); // 然后初始化事件监听器
  console.log('Event listeners initialized');
}

// 在页面加载完成后初始化游戏
window.addEventListener('load', function() {
  console.log('Page loaded, initializing game...');
  
  // 立即初始化DOM元素
  initDOM();
  
  // 添加全局错误处理
  window.addEventListener('error', function(event) {
    console.error('JavaScript Error:', event.message, event.filename, event.lineno);
  });
  
  // 直接在页面加载后绑定开始按钮点击事件，作为最保险的方案
  setTimeout(() => {
    const startButton = document.getElementById('start-button');
    if (startButton) {
      console.log('DIRECT BIND: Adding onclick to start button');
      startButton.onclick = function() {
        console.log('DIRECT BUTTON CLICK: Start button clicked');
        
        // 手动隐藏开始屏幕
        const startScreen = document.getElementById('start-screen');
        if (startScreen) {
          startScreen.style.display = 'none';
          console.log('Manually hid start screen');
        }
        
        // 手动显示游戏屏幕
        const gameScreen = document.getElementById('game-screen');
        if (gameScreen) {
          gameScreen.style.display = 'flex';
          console.log('Manually displayed game screen');
        }
        
        // 手动设置游戏状态并初始化游戏
        gameState.isPlaying = true;
        gameState.isPaused = false;
        console.log('Setting game state manually');
        
        // 调用initGame
        console.log('Calling initGame directly');
        initGame();
      };
    }
  }, 100); // 短暂延迟确保DOM完全加载
  
  init();
});